import { getTagData, Uint8Array2HexStr, fnamefixed, getDatasetData } from "../../../utils/util"
import {Web_Socket} from '../../../utils/socket'
import { operationCode } from "../../../utils/config";

const token = "token123";
const code = operationCode

const codeObj = {
    [code.bingdingController]: {title: "绑定控制器", filed: 'binding'},
    [code.unbingdingController]: {title: "解绑控制器", filed: 'binding'},
    [code.lockingController]: {title: "锁定控制器", filed: 'locking'},
    [code.unlockingController]: {title: "智控控制器", filed: 'locking'},
    [code.setLinkingPassword]: {title: "设置联机密码", filed: ''},
    [code.updateLinkingPassword]: {title: "修改联机密码", filed: ''},
    [code.updateAccessPassword]: {title: "修改访问密码", filed: ''}
}

const  disable = {
    link: 'linkDisable',
    access: 'accessDisable',
    getKey: (bCode) => {
        return bCode === code.updateAccessPassword ? 'accessDisable' : 'linkDisable'
    }
}



Page({

    /**
     * 页面的初始数据
     */
    data: {
        colorPrimary: wx.$theme.color,
        buttons: [{ text: '取消', extClass: 'dialogCancel1' }, { text: '确定', extClass: 'dialogConfirm1'}],
        halfScreenButtons: [{ type: 'default', text: '取消', className: 'dialogCancel' }, {type: 'primary',  text: '确定', className: 'dialogConfirm' }],
        formData:  {},
        binding: false,
        locking: false,
        hasLinkPassword: !1, //是否已设置连接密码
        linkingCode: code.setLinkingPassword//默认为设置密码指令
    },

    /**分组 */
    tapGroup() {
        this.setData({
            [`halfScreen.show`]: !0
        })
    },

    /**绑定 */
    tapBinding: function(e) {
        const {value} = e.detail;
        this.setData({binding: !value})
        const {device} = this.data;
        const message = {
            deviceKey: device.dkey,
            kvMap: {
                [value ? code.bingdingController : code.unbingdingController]: [1],
                [code.token]: token
            }
        }
        this.postOthers(message); 
    },

    /**锁定 */
    tapLocking: function(e) {
        const {device} = this.data;
        const {value} = e.detail;
        this.setData({locking: !value})
        const message = {
            deviceKey: device.dkey,
            kvMap: {
                [value ? code.lockingController : code.unlockingController]: [1],
                [code.token]: token
            }
        }
        this.postOthers(message);
    },

    /**灯具加密 */
    tapLampsEncrypted: function(e) {
        const {device} = this.data;
        const {value} = e.detail;
        this.setData({lamps: !value})
        this.tempSwitch.lamps = value
        const message = {
            deviceKey: device.dkey,
            kvMap: {
                [value ? code.lampsEncryptedOn : code.lampsEncryptedOff]: [1],
                [code.token]: token
            }
        }
        this.postOthers(message)
    },

    tapDelete: function() {
        wx.$http.delete({url: '/szm/device', data: [this.data.deviceId]}).then(() => {
            wx.showToast({
              title: '删除成功',
            })
            wx.removeStorageSync('link_pwd_' + this.data.dkey)
            setTimeout(() => {
                wx.navigateBack()
            }, 2000);
        })
    },

    // tapSetLinkingPassword: function() {
    //     this.disableTap({key: disable.link, reslove: () => {
    //         this.setData({
    //             dialogObj: {
    //                 show: true,
    //                 title: '设置联机密码',
    //                 placeholder: '请输入联机密码',
    //                 code: code.setLinkingPassword,
    //                 clear: '',
    //                 tips: false
    //             }
    //         });
    //         this.getLinkingPassword(this.data.device.dkey);
    //     }})
    // },

    tapResetBindingPassword: function() {
        this.disableTap({key: disable.access, reslove: () => {
            this.setData({
                dialogObj: {
                    show: true,
                    title: '修改访问密码',
                    placeholder: '请输入新的访问密码',
                    code: code.updateAccessPassword,
                    clear: '',
                    tips: false
                }
            })
        }});
    },

    disableTap({key, reslove}) {
        const time = wx.getStorageSync(key)
        if (!time || Date.now() - time > 30000) {
            reslove && reslove()
        } else {
            wx.showToast({
              title: `禁用${30 - Math.floor(( Date.now() - time)/1000)}秒`,
              icon: 'none'
            })
        }
    },

    /**联机密码，访问密码弹窗回调 */
    tapDialogButton: function(e) {
        if (!e.detail.index) {
            this.setData({[`dialogObj.show`]: false})
            return
        }
        let bCode = getTagData(e, 'code');
        this.setPassword(bCode);
    },

    /**联机按钮 */
    tapLinking: function(e) {
        const {formData, linkingCode} = this.data;
        if(formData[linkingCode]) {
            this.disableTap({key: disable.link, reslove: () => {
                this.setPassword(linkingCode);
            }})
        } else {
            wx.showToast({
              title: '请输入联机密码',
              icon: 'none'
            })
        }
    },

    setPassword(bCode) {
        const {device, formData} = this.data;
        console.log(bCode, formData[bCode])
        if(!formData[bCode] || !/^[0-9]{6}$/.test(formData[bCode])) {
            wx.showToast({
              title: '密码长度6位',
              icon: 'none'
            })
            return;
        }
        if ([code.setLinkingPassword, code.updateLinkingPassword].includes(bCode) && !/^[0-9]{6}$/.test(formData[bCode])) {
            wx.showToast({
                title: '联机密码为6位数字',
                icon: 'none'
            })
            return false;
        }

        this.setData({[`dialogObj.show`]: false})
     
        wx.setStorageSync(disable.getKey(bCode), Date.now());
        const message = {
            deviceKey: device.dkey,
            kvMap: {
                [bCode]: [...formData[bCode]].map(i => i.charCodeAt()),
                [code.token]: token
            }
        }
        this.postOthers(message);
    },

    async postOthers(message) {
        const {deviceKey, kvMap} = message;
        Object.keys(kvMap).forEach(i => console.log(`device页面 ${deviceKey}=>请求`, `指令Hex[${parseInt(i).toString(16).toUpperCase().padStart(4, '0')}]`, `值Hex[${Uint8Array2HexStr(kvMap[i], ',')}]`))
        await wx.$http.post({url: '/szm/netty/postOthers', data: message})
        this.setData({showLoading: 1})
    },

    getOnline(message) {
        return wx.$http.post({url: '/szm/netty/online', data: message})
    },

    async initData() {
        const {deviceId} = this.data
        try {
            const {data} = await wx.$http.get({url: `/szm/device/${deviceId}`})
            const groupName = data.placeName ? (data.placeName + (data.roomName ? ('-' + data.roomName) : '')) : '未分组'
            this.setData({
                device: Object.assign({groupName}, data),
                online: 1
            }, () => {
                this.getPlaceRoomDTO();
            })
        } catch (error) {
            this.setData({online: 0});
        }
    },

    /**盒子数据 */
    async initHubData() {
        try {
            const {dkey} = this.data;
            const message = {deviceKey: dkey}
            await this.getOnline(message)
            this.getLinkingPassword(dkey);
            setTimeout(() => {
                this.checkAllState(dkey);
            }, 200);
        } catch (error) {
            console.error(error)
        }
    },

    /**查询联机,绑定，锁定状态 */
    checkAllState(dkey) {
        const message3 = {
            deviceKey: dkey || this.data.device.dkey,
            kvMap: {
                [code.allStatus]: [1],
                [code.token]: token
            }
        }
        this.postOthers(message3)
    },

    //查询是否已设置联机密码
    getLinkingPassword(dkey) {
        const message = {
            deviceKey: dkey || this.data.device.dkey,
            kvMap: {
                [code.getLinkingPassword]: [1],
                [code.token]: token
            }
        }
        this.postOthers(message); 
    },

    /**查询灯控和盒子的联机密码是否一致 */
    checkPassword() {
        const message = {
            deviceKey: this.data.device.dkey,
            kvMap: {
                [code.checkPassword]: [0x01],
                [code.token]: token
            }
        }
        this.postOthers(message);
    },

    /**查询灯控是否有响应 */
    checkControllerRespond() {
        const message = {
            deviceKey: this.data.device.dkey,
            kvMap: {
                [code.checkControllerRespond]: [0x01],
                [code.token]: token
            }
        }
        this.postOthers(message);
    },

    [fnamefixed(code.getLinkingPassword)](data){
        console.log('===========', data)
        this.setData({
            linkingCode: data.length > 1 ? code.updateLinkingPassword : code.setLinkingPassword,
            [`formData.${code.updateLinkingPassword}`]: String.fromCharCode(...data)
        })
    },

    [fnamefixed(code.allStatus)](data){
        this.setData({
            linkOnline: data[0],
            binding: data[1],
            locking: data[2],
            lamps: data[3]
        });
        if (!data[0]) {//联机状态离线，检查（盒子和灯控的联机）联机密码是否一致，灯控是否有响应
            this.checkPassword();
            setTimeout(() => {
                this.checkControllerRespond();
            }, 2000);
        }
    },

    [fnamefixed(code.checkPassword)](data){
        if (!data[0]) {
            wx.showToast({
              title: '联机密码不一致',
              icon: 'none'
            })
        }
    },

    /**灯具开启加密返回 */
    [fnamefixed(code.lampsEncryptedOn)](data){
        if (data[0]) {
            this.setData({lamps: 1})
            wx.showToast({
              title: `开启加密`,
            })
        } else {
            wx.showToast({
              title: '开启加密失败',
              icon: 'none'
            })
        }
    },
    /**灯具关闭加密返回 */
    [fnamefixed(code.lampsEncryptedOff)](data){
        if (data[0]) {
            this.setData({lamps: 0})
            wx.showToast({
              title: `取消加密`,
            })
        } else {
            wx.showToast({
              title: '取消加密失败',
              icon: 'none'
            })
        }
    },

    [fnamefixed(code.checkControllerRespond)](data){
        if (!data[0]) {
            wx.showToast({
              title: '灯控无响应',
              icon: 'none'
            })
        }
    },

    socketOnMessage(name) {
        wx.$eventEmitter.off(name);
        wx.$eventEmitter.on(name, data => {
            this.setData({showLoading: 0})
            const { kvMap } = data;
            Object.keys(kvMap).forEach(k => {
                const bCode = parseInt(k);
                const value = kvMap[bCode][0] === 0x01;
                if ([code.bingdingController, code.lockingController].includes(bCode)) {
                    this.setData({[codeObj[bCode].filed]: value ? 1 : 0});//绑定和锁定 成功则打开开关
                } else if ([code.unbingdingController, code.unlockingController].includes(bCode)) {
                    this.setData({[codeObj[bCode].filed]: !value ? 1 : 0});//解绑和智控 成功则关闭开关
                } else if ([code.setLinkingPassword, code.updateLinkingPassword].includes(bCode)) {
                    wx.removeStorageSync(disable.link);
                    if(value && bCode === code.setLinkingPassword) {//成功则设置linkingCode
                        const {formData} = this.data;
                        formData[code.updateLinkingPassword] = formData[code.setLinkingPassword];
                        formData[code.setLinkingPassword] = '';
                        this.setData({
                            linkingCode: code.updateLinkingPassword,
                            formData
                        });
                    }
                } else if ([code.updateAccessPassword].includes(bCode) ) {
                    wx.removeStorageSync(disable.access)
                }

                //有title的指令提示成功失败
                if (codeObj[bCode] && codeObj[bCode].title) {
                    wx.showToast({
                        title: codeObj[bCode].title,
                        icon: value ? 'success' : 'none' 
                    })
                }

                const fucnName = fnamefixed(bCode);
                this[fucnName] && this[fucnName](kvMap[bCode])
            });
          
        })
    },

    tapEyes: function(e) {
        this.setData({
            showPassword: !this.data.showPassword
        });
    },

    tapAccessEyes: function(e) {
        this.setData({
            showAccessPassword: !this.data.showAccessPassword
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.socketOnMessage('device');
        const {id, dkey} = options
        wx.setStorageSync('deviceKey', dkey)
        this.setData({deviceId: id, dkey});
        this.tempSwitch = {};
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        const linkPwd = wx.getStorageSync('link_pwd_' + this.data.dkey);
        if (linkPwd && linkPwd.length > 1) {
            this.setData({
                linkingCode: code.updateLinkingPassword,
                [`formData.${code.updateLinkingPassword}`]: String.fromCharCode(...linkPwd)
            });
        }

        this.initData();
        this.initHubData();
        Web_Socket.buildSocket('device');
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    tapScheduleLock: function() {
        wx.navigateTo({
          url: `../../schedule/index?id=${this.data.deviceId}`,
          success(res) {
            res.eventChannel.emit("deviceKeys", {keys: [wx.getStorageSync('deviceKey')], countEdun: 1});
        }
        })
    },

    inputChange(e) {
        const {field} = getDatasetData(e)
        this.setData({
            [`formData.${field}`]: e.detail.value
        })
    },
    bindblur: function(e) {
        setTimeout(() => {
            const {field} = e.mark;
            this.setData({[`edit.${field}`]: false});
        }, 3000)
    },
    inputfocus: function (e) {
        const {field} = e.mark;
        this.setData({[`edit.${field}`]: true});
    },

    /**保存名称 */
    tapSave: function(e) {
        const {field} = e.mark;
        const {deviceId, formData} = this.data;
        wx.$http.put({url: '/szm/device', data: {id: deviceId, [field]: formData[field]}}).then(res => {
            this.setData({[`edit.${field}`]: false});
            wx.showToast({
                title: '保存成功',
            });
            this.initData();
        });
    },

    tapCopyIccid: function (params) {
        const {iccid} =  this.data.device;
        iccid && wx.setClipboardData({
            data: iccid,
          });
    },

     /**关闭半屏弹窗回调 */
     tapHalfButton: function(e) {
		this.setData({
            [`halfScreen.show`]: !1
        })
        const {deviceId, halfScreen} = this.data;
        const placeId = halfScreen.list0[halfScreen.index[0]].id;
        const roomId = halfScreen.list1[halfScreen.index[1]] ? halfScreen.list1[halfScreen.index[1]].id : 0;
        wx.$http.put({url: '/szm/device', data: {id: deviceId, placeId, roomId}}).then(res => {
            wx.showToast({
                title: '分组',
            });
            this.initData();
        });
        
    },

    halfScreenChange: function(e) {
        const values = e.detail.value;
        this.setData({
            [`halfScreen.index`]: values
        })
        this.setData({
            [`halfScreen.list1`]: this.data.halfScreen.list0[values[0]].child
        })
    },
    getPlaceRoomDTO() {
        wx.$http.get({url: '/szm/place/actionSheet'}).then(res => {
            if (res.data && res.data.length > 0) {
                const list0 = res.data;
                let list1 = res.data[0].child || [];
                const {placeId, roomId} = this.data.device;
                const indexs = [0, 0];
                if (parseInt(roomId) > 0) {
                    const index0 = list0.findIndex(l => l.id === placeId);
                    list1 = list0[index0].child;
                    const index1 = list1 && list1.length > 0 ? list1.findIndex(l => l.id === roomId) : 0;
                    indexs[0] = index0;
                    indexs[1] = index1;
                }
                this.setData({
                    [`halfScreen.list0`]: list0,
                    [`halfScreen.list1`]: list1
                });
    
                this.setData({
                    [`halfScreen.index`]: indexs
                })
            }
        });
    },

    hideLoading: function (params) {
        
    }
})